package com.qf.rbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.rbac.sys.entity.SysRoleMenu;
import com.qf.rbac.sys.mapper.SysRoleMenuMapper;
import com.qf.rbac.sys.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Override
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        //先删除角色与菜单关系
        deleteBatch(new Long[]{roleId});

        if(menuIdList.size() == 0){
            return ;
        }

        //保存角色与菜单关系
        for(Long menuId : menuIdList){
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(roleId);

            this.save(sysRoleMenu);
        }
    }

    @Override
    public boolean deleteBatch(Long[] roleIds) {
//        return this.removeBatchByIds(Arrays.asList(roleIds));
        for (Long roleId : roleIds) {
            this.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,roleId));
        }
        return true;
    }

    @Override
    public List<Long> queryMenuIdList(Long roleId) {
        List<SysRoleMenu> list = list(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,roleId));
        List<Long> collect = list.stream().map((Function<SysRoleMenu, Long>) sysRoleMenu -> sysRoleMenu.getMenuId()).collect(Collectors.toList());
        return collect;
    }


}
